<?php

namespace App\Jobs;

use App\Models\Admin\AdminUser;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Mail;

class SendEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $name;
    protected $email;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($name,$email)
    {
        //
        $this->name=$name;
        $this->email=$email;
    }

    /**
     * 执行队列
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //如果尝试大于3次失败
        if($this->attempts()>1) {
            \Log::info($this->name.'邮件尝试失败过多');
        } else {
            //每次进来休息3秒
            sleep(1);
            //Mail send:第一个参数是视图文件 Mail raw是直接发送原生字符串邮件
//            Mail::raw('this is a test email',function($message){
//                $message->to($this->email)->subject('邮件测试');
//            });
            //Mail send
            Mail::send('mail.test',function($message){
                $message->to($this->email)->subject('邮件测试');
            });

            echo $this->name;

            //通过返回的错误参数 判断邮件发送成功还是失败
            if(count(Mail::failures())<1) {
                \Log::info($this->name.'邮件发送成功'.count(Mail::failures()));
            } else {
                \Log::info($this->name.'邮件发送失败');
            }

        }
    }

    public function failed()
    {
        \Log::error($this->name.'队列任务执行失败'."\n".date('Y-m-d H:i:s'));
    }
}
